package com.ninth_group.service.Impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.ninth_group.constant.PCWConstants;
import com.ninth_group.constant.WeatherCode;
import com.ninth_group.dao.PCWeatherInfoDao;
import com.ninth_group.mapper.PCWeatherInfoMapper;
import com.ninth_group.po.PCWeatherInfo;
import com.ninth_group.service.PCWeatherInfoService;
import com.ninth_group.utils.ReuseCodeService;
import com.ninth_group.vo.PCWeatherInfoVO;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class PCWeatherInfoServiceImpl implements PCWeatherInfoService {

    @Resource
    private PCWeatherInfoDao pcWeatherInfoDao;
    @Resource
    private ReuseCodeService reuseCodeService;

    /**
     * 获取所有省会天气信息
     * @return List<PCWeatherInfoVO>
     */
    @Override
    public List<PCWeatherInfoVO> getPCWeatherInfo() throws JsonProcessingException {
        // 从redis中获取数据
        List<PCWeatherInfoVO> dataFromRedis = reuseCodeService.getDataFromRedis(
                PCWConstants.ALL_PROVINCE_WEATHER_INFO, PCWeatherInfoVO.class);

        // redis存在缓存
        if (!dataFromRedis.isEmpty()) return dataFromRedis;

        // 查询数据库并添加到redis中
        List<PCWeatherInfo> pcWeatherInfo = pcWeatherInfoDao.getPCWeatherInfo();

        // 转换为vo
        List<PCWeatherInfoVO> vo = PCWeatherInfoMapper.INSTANCE.toVo(pcWeatherInfo);

        // 给weatherCode赋值
        for (PCWeatherInfoVO pcWeatherInfoVO : vo) {
            pcWeatherInfoVO.setWeatherCode(WeatherCode.getCodeByWeather(pcWeatherInfoVO.getWeather()));
        }

        reuseCodeService.addToRedis(vo, PCWConstants.ALL_PROVINCE_WEATHER_INFO,
                PCWConstants.CACHE_TIME, TimeUnit.MINUTES);
        return vo;
    }
}
